from flask import Flask, jsonify, request
from config import config_rabbit
from utils.rabbit_mq import RabbitBase
from utils.logger import debug,error
from utils.judge import JudgeHandle
import json
from utils.exception import CompileError



app = Flask(__name__)

rabbit_data = RabbitBase(  # 实时数据入库队列对象
    config_rabbit['rabbit_host'], config_rabbit['rabbit_port'], 
    config_rabbit['rabbit_user'], config_rabbit['rabbit_pwd'], 
    config_rabbit['virtual_host'], config_rabbit['store_queue'])


@app.route('/hello')
def hello():
    return jsonify({'code': 200, 'result': u'Method Get Is Not Allow'})

@app.route('/judge', methods=['POST'])
def judge():
    data = request.get_data()
    try:
        res = JudgeHandle._handle(json.loads(data))
    except CompileError as e:
        return jsonify({'code': 500, 'result': e.message})
    return jsonify({'code': 200, 'result': res})

@app.route('/publish', methods=['POST'])
def publish():
    data = request.form.get('data')
    rabbit_data.publish(data)
    return jsonify({'code': 200, 'result': u'发布成功'})

@app.route('/consume')
def consume():
    if (rabbit_data.is_working == False):
        rabbit_data.start_consuming()
    return jsonify({'code': 200, 'result': u'消费程序已经启动'})

@app.route('/insert')
def insert():
    try:
        return jsonify({'code': 200, 'result': u'插入成功'})
    except Exception as e:
        error(e)
        return jsonify({'code': 200, 'result': u'插入失败'})

def run():
    host = "0.0.0.0"
    port = 5000
    app.run(host=host, port=port, debug=True)


if __name__ == "__main__":
    run()
